package com.jsp.controller.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class CookieFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        try{
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //1.获取资源请求路径
        String uri = request.getRequestURI();
        //2.判断是否包含登录相关资源路径,要注意排除掉 css/js/图片/验证码等资源
        if(uri.contains("/index.jsp") || uri.contains("/userLogin") || uri.contains("/css/") || uri.contains("/js/")  ) {
            //包含，用户就是想登录。放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName())) {
                    if (null != cookie.getValue()) {
                        filterChain.doFilter(servletRequest,servletResponse);
                        return;

                    }
                }
            }
        }
        request.getRequestDispatcher("/index.jsp").forward(request, servletResponse);
        }catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}

